<template>
  <div id="pushIndex">
    <div class="select-group">
      <div class="items">
        <span class="items-text">转化时间</span>
        <el-date-picker
          v-model="query.timeValue"
          type="daterange"
          unlink-panels
          value-format='yyyy-MM-dd'
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickOption">
        </el-date-picker>
      </div>
      <el-button :disabled="listLoading" @click="getList" size="medium" type="success" class="el-icon-search searchBtn">
        <span style="padding-left:5px;">查询</span>
      </el-button>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">客服</span>
        <el-select v-model="query.userId"
                   clearable
                   @change="customChange"
                   filterable
                   placeholder="请选择">
          <el-option
            v-for="item in customUserList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">关键词</span>
        <el-select v-model="query.keyword"
                   clearable
                   filterable
                   placeholder="请选择">
          <el-option
            v-for="(item,idx) in keywordList"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="items">
        <span class="items-text">系统标签</span>
        <el-select v-model="query.sysLabel" clearable filterable placeholder="请选择">
          <el-option
            v-for="(item,idx) in systemlabel"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="select-group">
      <div class="items">
        <span class="items-text">客服标签</span>
        <el-select v-model="query.defineLabel"
                   clearable
                   filterable
                   multiple
                   placeholder="请选择">
          <el-option
            v-for="(item,idx) in userLabelList"
            :key="idx"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="items">
        <span class="items-text">号码归属地</span>
        <el-cascader
          filterable
          clearable
          change-on-select
          :options="areaList"
          v-model="query.areaOptions">
        </el-cascader>
      </div>
    </div>


    <div>
      <h4 style="float: left;display: inline-block">
        转化数据表
      </h4>
      <div v-if="userInfo.roleId != 1" style="display:inline-block;float: right;margin-right: 80px">
        <el-button
          class="eventBtn"
          type="primary"
          @click="batchEvent(false)"
          size="small"
          icon="el-icon-edit-outline">
          选中推送
        </el-button>
        <el-button
          class="eventBtn"
          type="primary"
          @click="batchEvent(true)"
          size="small"
          icon="el-icon-edit-outline">
          批量推送
        </el-button>
      </div>

    </div>

    <el-dialog width="400px"
               title="分配"
               :visible.sync="infoFormVisible"
               @close="cancledialog('sendForm')"
    >

      <el-form :model="allot"  :rules="rules" ref="sendForm">
        <!--这里必须套一个div 不然先点击批量后点击选中  弹框关闭时会报错-->
        <div>
          <el-form-item label="当前已选择 : "
                        v-show="!isBatch"
                        :label-width="formLabelWidth">
            <span>{{ multipleSelection.length }} 条</span>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="batchCount"
                        v-if="isBatch"
                        label="推送数量"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.number.sync="allot.batchCount" type="number" placeholder="请输入"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="folder"
                        label="批次名称"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.sync="allot.folder"  placeholder="请输入批次名称"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="目标机构" prop="orgId" :label-width="formLabelWidth">
            <el-select v-model="allot.orgId" clearable multiple filterable placeholder="请选择">
              <el-option
                v-for="item in orgList"
                :key="item.value"
                :label="item.orgName"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-if="isBatch">
          <el-form-item label="当前总条数 : "
                        :label-width="formLabelWidth">
            <span>{{ totalTemp }} 条</span>
          </el-form-item>
        </div>
        <div v-if="isBatch" class="batchMark">
          {{ '注释: 适用于大批量数据推送。输入想要推送的数据数量，选择目标公司。' + ('(一次最多推送'+ maxBatchNum +'条)')  }}
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="() => isBatch ? batchSendEvent() : sendEvent()">分配</el-button>
        <el-button @click="infoFormVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog width="400px"
               title="编辑呼叫记录"
               :visible.sync="callVisible"
               @close="cancledialog('callForm')"
    >
      <el-form :model="itemRowData"  :rules="rulesCall" ref="callForm">
          <el-form-item prop="phone"
                        label="手机号码"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.sync="itemRowData.phone" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item
                        label="意向项目"
                        :label-width="formLabelWidth">
            <el-input style="width: 200px;" v-model.sync="itemRowData.item"  placeholder="请输入意向项目"></el-input>
          </el-form-item>
        <el-form-item
                      label="客服备注"
                      :label-width="formLabelWidth">
          <el-input style="width: 200px;" type="textarea" :autosize="{ minRows:3,maxRows:5 }"  v-model.sync="itemRowData.remarks"  placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="pushUpdate">确定</el-button>
        <el-button @click="callVisible = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <el-table empty-text="暂无任何数据信息"
              @selection-change="handleSelectionChange"
              :data="list"
              v-loading.body="listLoading"
              border
              fit
              style="width: 100%">
      <el-table-column
        align="center"
        type="selection"
        width="40">
      </el-table-column>
      <el-table-column align="center" label="数据ID" >
        <template slot-scope="scope">
          <span>{{scope.row.customerName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="关键信息">
        <template slot-scope="scope" style="text-align:left">
          <p v-if='!scope.row.keyInfo'>-</p>
          <div v-else>
            <p :key="idx" v-for=" (tmp,idx) in scope.row.keyInfo.split('$') ">
              {{tmp}}
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="关键词">
        <template slot-scope="scope">
          <p :key="idx" v-for=" (tmp,idx) in scope.row.word">
            {{tmp}}
          </p>
        </template>
      </el-table-column>

      <el-table-column align="center" label="系统标签">
        <template slot-scope="scope">
          <p :key="idx" v-for=" (tmp,idx) in scope.row.label">
            {{tmp}}
          </p>
        </template>
      </el-table-column>

      <el-table-column align="center" label="客服标签">
        <template slot-scope="scope" style="text-align:left">
          <p v-if='!scope.row.userLabel'>-</p>
          <div v-else>
            <p :key="idx" v-for=" (tmp,idx) in scope.row.userLabel.split('$') ">
              {{tmp}}
            </p>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="呼叫备注">
        <template slot-scope="scope">
          <span>{{ scope.row.remarks ? scope.row.remarks : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="号码归属地">
        <template slot-scope="scope">
          <span>{{ scope.row.provinceName ?  (scope.row.provinceName + ( scope.row.cityName === '' ? '' :  '/' + scope.row.cityName )) : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="客服">
        <template slot-scope="scope">
          <span>{{ scope.row.userName ?  scope.row.userName : '-'}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="转化时间">
        <template slot-scope="scope">
          <span>{{ scope.row.callTime ?  scope.row.callTime.split('.')[0] : '-'}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="一键转接">
        <template slot-scope="scope">
          <span>{{ scope.row.exchange && scope.row.exchange == 1 ? '未转接' : "已转接" }}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="操作" width="220">
        <template slot-scope="scope">
          <router-link @click.native="saveLocal(scope.row)"  style="margin-right: 9px;" :to="{path:'/datapush/detail'}">
            <el-button type="primary" size="small" >详情</el-button>
          </router-link>
          <el-button  @click="openCallDialog(scope.row)"  type="success" size="small" >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange" :current-page.sync="query.current"
                     :page-sizes="[10,20,30,50]" :page-size="query.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getCustom, getKeyword } from "@/api/chart";
import {
  getSysLabel,
  getCustomerLabel,
  getPushList,
  getOrgList,
  pushSelect,
  pushBatch,
  pushUpdate
} from "@/api/datapush";
import { getAreaList } from "@/api/dataStock";
import { filterObj, transformTimeValue } from "@/utils/index";

export default {
  name: "datapush",
  data() {
    const CheckBatchNum = (rule, value, callback) => {
      let tempValue = value * 1;
      let maxNum =
        this.totalTemp > this.maxBatchNum ? this.maxBatchNum : this.totalTemp;
      if (!value) {
        callback(new Error("请输入要分配的条数"));
      } else if (!Number.isInteger(tempValue) || tempValue < 1) {
        this.allot.batchCount = "";
        callback(new Error("输入必须是大于0的数字"));
      } else if (tempValue > maxNum) {
        this.allot.batchCount = "";
        callback(
          new Error(
            maxNum >= this.maxBatchNum
              ? "单次处理不能大于" + maxNum + "条数"
              : "输入值不能大于" + maxNum + "条数"
          )
        );
      } else {
        callback();
      }
    };
    const isPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号码"));
      } else if (value.length != 11) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      itemRowData: {},
      callVisible: false,
      maxBatchNum: 2000,
      allot: {
        folderName: "",
        orgId: [],
        batchCount: null
      },
      formLabelWidth: "120px",
      isBatch: false,
      multipleSelection: [],
      infoFormVisible: false,
      listLoading: false,
      total: 0,
      totalTemp: 0,
      list: [],
      query: {
        timeValue: [],
        userId: "",
        keyword: "",
        sysLabel: "",
        defineLabel: [],
        areaOptions: [],
        pagesize: 10,
        current: 1
      },
      pickOption: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      orgList: [],
      customUserList: [],
      keywordList: [],
      systemlabel: [],
      userLabelList: [],
      areaList: [],
      rules: {
        orgId: [
          {
            type: "array",
            required: true,
            message: "请选择目标机构",
            trigger: "change"
          }
        ],
        batchCount: [{ validator: CheckBatchNum, trigger: "blur" }],
        folder: [{ required: true, message: "请填写批次名称", trigger: "blur" }]
      },
      rulesCall: {
        phone: [{ validator: isPhone, trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["userInfo"])
  },
  created() {
    if (this.userInfo.roleId == 1 && !this.userInfo.companyId) {
      this.$message.error("当前身份没有companyId,请去首页设置临时公司身份");
    } else {
      this.query.companyId = this.userInfo.companyId;
      this.getOpions();
      this.getList();
    }
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    $route(to, from) {
      if (to.path === "/datapush/index") {
        if (this.userInfo.roleId == 1 && !this.userInfo.companyId) {
          this.$message.error("当前身份没有companyId,请去首页设置临时公司身份");
        } else {
          this.query.companyId = this.userInfo.companyId;
          this.getOpions();
          this.getList();
        }
      }
    }
  },
  methods: {
    customChange() {
      this.keywordList = [];
      this.systemlabel = [];
      this.query.keyword = "";
      this.query.sysLabel = "";

      this.getKeyword();
      this.getSysLabel();
    },
    getList() {
      let temp = this.filterObj(this.transformTimeValue(this.query));
      this.listLoading = true;
      getPushList(temp)
        .then(res => {
          let temp = res.data.info;
          this.list = temp;
          this.total = res.data.total * 1;
          //把当前总条数给  totalTemp
          this.totalTemp = res.data.total * 1;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
          this.$message.error(res);
        });
    },
    getOpions() {
      this.getCustomData();
      this.getCustomerLabel();
      this.getKeyword();
      this.getSysLabel();
      this.getAreaList();
      this.getOrgList();
    },
    getOrgList() {
      getOrgList()
        .then(res => {
          let temp = res.data.info;
          this.orgList = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    getCustomData() {
      //获取客服列表
      return new Promise((resolve, reject) => {
        let tempData = { companyId: this.query.companyId };
        getCustom(tempData)
          .then(res => {
            this.customUserList = res.data.user;
            resolve();
          })
          .catch(res => {
            this.$message.error(res);
            reject();
          });
      });
    },
    getKeyword() {
      let temp = this.filterObj(this.transformTimeValue(this.query), [
        "companyId",
        "userId",
        "start",
        "end"
      ]);
      getKeyword(temp)
        .then(res => {
          let temp = res.data.keyword;
          this.keywordList = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    getSysLabel() {
      let temp = this.filterObj(this.transformTimeValue(this.query), [
        "companyId",
        "userId",
        "start",
        "end"
      ]);
      getSysLabel(temp)
        .then(res => {
          let temp = res.data.sysLabel;
          this.systemlabel = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    getAreaList() {
      getAreaList()
        .then(res => {
          let temp = res.data.area;
          this.areaList = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    getCustomerLabel() {
      getCustomerLabel()
        .then(res => {
          let temp = res.data.label;
          this.userLabelList = temp;
        })
        .catch(res => {
          this.$message.error(res);
        });
    },
    pushUpdate() {
      this.$refs.callForm.validate(valid => {
        if (!valid) {
          return;
        }

        let tar_rowData = this.itemRowData;
        let temp = {
          customerId: tar_rowData.customerId,
          phone: tar_rowData.phone,
          item: tar_rowData.item,
          callTime: tar_rowData.callTime,
          remarks: tar_rowData.remarks
        };
        pushUpdate(temp)
          .then(res => {
            this.callVisible = false;
            this.$message.success({
              message: res.msg,
              duration: 1000,
              onClose: () => {
                this.getList();
              }
            });
          })
          .catch(res => {
            this.callVisible = false;
            this.$message.error(res);
          });
      });
    },
    filterObj,
    transformTimeValue,
    handleSelectionChange(val) {
      this.multipleSelection = val.map(v => v.customerId);
    },
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.query.current = val;
      this.getList();
    },
    batchEvent(bool) {
      //控制是否是批量操作
      this.infoFormVisible = true;
      this.isBatch = bool;
    },
    cancledialog(userForm) {
      //重置表单
      this.$refs[userForm].resetFields();
    },
    saveLocal(item) {
      let local_user = localStorage.getItem("PUSH_DATA");
      !!local_user ? localStorage.removeItem("PUSH_DATA") : null;
      localStorage.setItem("PUSH_DATA", JSON.stringify(item));
    },
    openCallDialog(rowData) {
      this.itemRowData = rowData;
      this.callVisible = true;
    },
    sendEvent() {
      //单个数据操作
      this.$refs.sendForm.validate(valid => {
        if (!valid) {
          return;
        }
        if (!this.multipleSelection.length && !this.isBatch) {
          //如果未选中一条
          this.infoFormVisible = false;
          this.$message.error("您未有选中的操作项");
          return;
        }
        let tempData = { customerId: this.multipleSelection };
        tempData["orgId"] = this.allot.orgId;
        tempData["folder"] = this.allot.folder;
        tempData["pushId"] = this.userInfo.userId;
        pushSelect(tempData)
          .then(res => {
            //完成后 再次请求列表
            this.getList();
            this.$message.success(res.msg);
            this.infoFormVisible = false;
          })
          .catch(res => {
            this.$message.error(res);
            this.infoFormVisible = false;
          });
      });
    },
    batchSendEvent() {
      //批量操作
      this.$refs.sendForm.validate(valid => {
        if (!valid) {
          return;
        }
        let fullLoading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        //是否点击的批量
        let tempData = {
          count: this.allot.batchCount,
          orgId: this.allot.orgId,
          folder: this.allot.folder,
          pushId: this.userInfo.userId
        };
        tempData = Object.assign(
          {},
          tempData,
          this.filterObj(
            this.transformTimeValue(this.query),
            ["pagesize", "current"],
            true
          )
        );
        pushBatch(tempData)
          .then(res => {
            fullLoading.close(); //关闭遮罩
            //完成后 再次请求列表
            this.getList();
            this.$message.success(res.msg);
            this.infoFormVisible = false;
          })
          .catch(res => {
            fullLoading.close(); //关闭遮罩
            this.$message.error(res);
            this.infoFormVisible = false;
          });
      });
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
#pushIndex {
  .searchBtn {
    margin-left: 80px;
  }
  .eventBtn {
    margin-left: 15px;
  }
}
</style>
